package com.thunbu.lib_common.base

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.Job
import java.util.concurrent.CancellationException


/**
 *Created by Chaolue.Fan on 2021/5/13
描述: 管理协程
 */
abstract class CoroutineViewModel<M> : ViewModel() {

    val TAG = this::class.java.simpleName
    val model = initModel()
    abstract fun initModel(): M


    val jobs = mutableListOf<Job>()


    fun Job.add2Jobs(): Job {
        jobs.add(this)
        return this
    }


    override fun onCleared() {
        super.onCleared()
        jobs.forEach {
            it.cancel(CancellationException("${it.hashCode()}取消协程"))
        }
    }

}